package com.gouaixin.bee.beeframework2.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.ab.util.AbToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gouaixin.bee.beeframework2.adapter.ZhenxinhuaLiaotianAdapter;
import com.gouaixin.bee.beeframework2.dao.ZhenxinhuaMsgDao;
import com.gouaixin.bee.beeframework2.tool.PreferencesUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.gouaixin.bee.beeframework2.MyAPI;
import com.gouaixin.bee.beeframework2.R;
import com.gouaixin.bee.beeframework2.bean.ZHENXINHUA;
import com.gouaixin.bee.beeframework2.bean.ZhenxinhuaFriend;
import com.gouaixin.bee.beeframework2.bean.ZhenxinhuaMsg;
import com.gouaixin.bee.beeframework2.dao.zhenxinhuaFriendDao;
import com.gouaixin.bee.beeframework2.bean.BaseModel;
import com.gouaixin.bee.beeframework2.model.ChatModel;
import com.gouaixin.bee.beeframework2.tool.mLog;
import com.lidroid.xutils.http.RequestParams;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by Administrator on 2015/3/10.
 */
//真心话界面
public class B23_zhenxinhuaActivity extends FragmentActivity {
    Context context = B23_zhenxinhuaActivity.this;

    //是否是我主动进入
    boolean isInitiative=false;

    //是否在等待机器人回答,并让机器人问一个问题
    boolean isWait=false;

    //是否显示提示可以问问题图标
    boolean isShowTishi=false;

    //顶部
    ImageView back;//返回
    TextView title;//标题
    ImageView right;//顶部右边图标

    //内容区
    ListView listView;
    ZhenxinhuaLiaotianAdapter adapter;
    List<ZhenxinhuaMsg> datas = new ArrayList<ZhenxinhuaMsg>();

    ImageView tishiBg;

    //底部
    EditText input;
    TextView send;

    String jid;
    String jicon;
    String jname;
    String cid;
    String cicon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.b23_zhenxinhua);
        Intent it = getIntent();
        initSoudPool();

        jid = it.getStringExtra("jid");
        jicon = it.getStringExtra("jicon");
        jname = it.getStringExtra("jname");
        cid = PreferencesUtils.getString(context, "cid");
        isInitiative=it.getBooleanExtra("isInitiative",false);
        isInitiative=it.getBooleanExtra("isInitiative",false);

        getHerData();//变成关注的


        initView();

//        initIntent();

        setData();

        setListener();

        setTishi();


        isJinzhiWen=PreferencesUtils.getBoolean(context,jid+"isJinzhiWen",false);
        mLog.e("isJinzhiWen="+isJinzhiWen);
        if(isJinzhiWen==true){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    receive();
                }
            }, 2000);

        }
    }



    //禁止问问题
    boolean isJinzhiWen;

    /***
     * 得到对象详情
     * @return
     */
    public  void getHerData() {
        String url="http://jiekou.hydgyx.com/api/interface_detail.php";

        RequestParams params = new RequestParams();
        params.addBodyParameter("id", jid);
        params.addBodyParameter("cid", PreferencesUtils.getString(context,"cid"));

        mLog.e("id=" + jid);
        mLog.e("cid=" + PreferencesUtils.getString(context, "id"));

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                url,
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                        mLog.e("conn...");
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        if (isUploading) {
                            mLog.e("upload: " + current + "/" + total);
                        } else {
                            mLog.e("reply: " + current + "/" + total);
                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        mLog.e("得到对象详情：响应值：reply: " + responseInfo.result);
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        mLog.e(error.getExceptionCode() + ":" + msg);
                    }
                });
    }



    //设置提示图标
    private void setTishi() {
        tishiBg= (ImageView) findViewById(R.id.tishiBg);

        if(isShowTishi){
            tishiBg.setVisibility(View.VISIBLE);
        }else {
            tishiBg.setVisibility(View.INVISIBLE);
        }


    }

    @Override
    protected void onResume() {
        super.onResume();

        //是否是从选问题界面返回
        if (!isResult) {
            mLog.e("恢复运行时读取的聊天记录：");
            datas = ZhenxinhuaMsgDao.queryWithId(context, jid, cid);
            adapter.setData(datas);
            adapter.notifyDataSetChanged();
            if (datas != null) {
                listView.setSelection(datas.size());
            }

            //如果没有消息，就接受机器人的一个消息
            if (datas == null || datas.size() == 0) {
                //如果是我主动进入的，就不接受消息
                if(isInitiative==true){
                    mLog.e("如果是我主动进入的，就不接受消息");
                }else{
                    mLog.e("如果没有消息，且非主动进入，就接受机器人的一个消息");


                    boolean jidHavaRecevieMsg=PreferencesUtils.getBoolean(context,jid+"havaRecevieMsg",false);
                    if(jidHavaRecevieMsg==false){
                        PreferencesUtils.putBoolean(context,jid+"havaRecevieMsg",true);

                        //在等待机器人时，禁止用户点击
                        isWait=true;



                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                receive();
                            }
                        }, 2000);
                    }

                }


            }
        }


    }

    private void initView() {
        back = (ImageView) findViewById(R.id.back);
        title = (TextView) findViewById(R.id.title);
        right = (ImageView) findViewById(R.id.back2);

        input = (EditText) findViewById(R.id.input);
        send = (TextView) findViewById(R.id.send);

        listView = (ListView) findViewById(R.id.listview);
        adapter = new ZhenxinhuaLiaotianAdapter(context);
        listView.setAdapter(adapter);



    }

//    private void initIntent() {
//        Intent it=getIntent();
//        Bundle bundle = it.getExtras();    //获取intent里面的bundle对象
//        if(bundle!=null){
//            ZHENXINHUA bean=(ZHENXINHUA)it.getSerializableExtra("zhenxinhua");
//            bean.setType(ZHENXINHUA.SEND);
//            mLog.e("答案："+bean.getDaan()[0]);
//            mLog.e("答案："+bean.getDaan()[1]);
//            mLog.e("答案："+bean.getDaan()[2]);
//
//
//            datas.add(bean);
//
//            adapter.setData(datas);
//            adapter.notifyDataSetChanged();
//        }
//
//
//    }

    private void setData() {
//        ZHENXINHUA bean=new ZHENXINHUA();
//        String wenti="你是好人吗？";
//        bean.setWenti(wenti);
//        String[]daan={"我是好人","我是坏人","我不是人"};
//        bean.setDaan(daan);
//        datas.add(bean);
//        datas.add(bean);
//        datas.add(bean);
//        datas.add(bean);
//        datas.add(bean);
//
//        adapter.setData(datas);
//        adapter.notifyDataSetChanged();

    }


    String daanDefult = "点击回答问题……";

    private void setListener() {
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, B24_zhenxinhuawentiActivity.class));
                finish();
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                AbToastUtil.showToast(context,"你选择的是："+position);
            }
        });

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLog.e("点击了send:000000");


                isJinzhiWen=PreferencesUtils.getBoolean(context,jid+"isJinzhiWen",false);
                mLog.e("isJinzhiWen="+isJinzhiWen);

                if(isJinzhiWen==true){
                    AbToastUtil.showToast(context, "亲，请等待对方回答问题或提问哦！");
                    return;
                }


                String temp = input.getText().toString();
                String daan="";
                if(datas==null||datas.equals("[]")||datas.size()==0){

                }else{
                    daan = datas.get(datas.size() - 1).getDaan();
                }


                mLog.e("点击了send:00000011111");
                //判断是否有需要回答的问题
                if (daanDefult.equals(daan) || haveWenti) {
                    AbToastUtil.showToast(context, "亲，你还没有回答问题哦！");
                    return;
                };
//
                mLog.e("点击了send:1111111");
                //判断是否在等待机器人回答
                if(isWait==true){
                    AbToastUtil.showToast(context, "亲，请等待对方回答问题或提问哦！");
                    return;
                }

                mLog.e("点击了send:222222222");



//                //判断当前用户是否可聊天
                //判断是否可以发送消息
                ChatModel.getSendable(context,jid, new ChatModel.MCallback() {
                    @Override
                    public void onCallBack(int type) {
                        mLog.e("接受回调的参数：type=" + type);

                        if(type==ChatModel.canSend){
                            //进入发送消息的实现方法
                            mLog.e("进入发送消息的实现方法");
                            mLog.e("点击了send:3333333333333");
                    isShowTishi=false;
                    setTishi();

                            send.setClickable(false);
                    Intent it = new Intent(context, B24_zhenxinhuawentiActivity.class);
                    it.putExtra("jid", jid);
                    startActivityForResult(it, 0);
                        }else if(type==ChatModel.toSendMoney){
                            //进入送话费的实现方法
                            mLog.e("进入送话费的实现方法");
                            toSendMoney();
                        }else{
//                    //弹出调转到包月界面的对话框
//                    DialogModel.toBaoyue(context, "立即开通包月服务，和心爱的她畅聊吧");
                            mLog.e("进入下一收费项目");
                            mLog.e("jname=" + jname);
                            ChatModel.toNextMemberType(context, jname);
                        }

                    }
                });

//                if (ChatModel.getSendable(context, jid)) {
//
//
//                    mLogUtil.e("点击了send:3333333333333");
//                    isShowTishi=false;
//                    setTishi();
//
//                    Intent it = new Intent(context, B24_zhenxinhuawentiActivity.class);
//                    it.putExtra("jid", jid);
//                    startActivityForResult(it, 0);
//                } else {
//                    mLogUtil.e("点击了send:44444444444");
//
//                    //弹出调转到包月界面的对话框
////                    DialogModel.toBaoyue(context, "立即开通包月服务，和心爱的她畅聊吧");
//                    mLogUtil.e("进入下一收费项目");
//                    ChatModel.toNextMemberType(context,jname);
//
//                }
            }
        });


        //点击回答问题的回调机制
        adapter.setCallBackLister(new ZhenxinhuaLiaotianAdapter.CallBackLister() {
            @Override
            public void onCallBack(int position) {
                mLog.e(" adapter.setCallBackLister");
                Intent it = new Intent(context, B25_zhenxinhuaHuidaActivity.class);
                startActivityForResult(it, 1);
            }
        });


    }


    /**
     * 去送话费的实现方法
     */
    private void toSendMoney() {
        Intent k1 = new Intent(context, paySuccessActivity.class);
        startActivity(k1);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mLog.e("进入返回结果：000000");
        switch (requestCode) {
            //当前用户选择问题
            case 0:
                send.setClickable(true);
                if (data != null) {
                    mLog.e("进入返回结果：" + 1111111);
                    wentiStr = data.getStringExtra("wenti");
                    daanStr = data.getStringExtra("daan");

                    mLog.e("返回的值：" + wentiStr);
                    mLog.e("返回的值：" + daanStr);

                    isResult = true;




                    send(wentiStr, daanStr);

                }


                break;
            //当前用户回答问题
            case 1:
                if (data != null) {
                    mLog.e("进入返回结果：" + 1111111);
                    daanStr = data.getStringExtra("daan");

                    mLog.e("返回的值：" + daanStr);

                    isResult = true;

                    huida(daanStr);

                }


                break;
        }


    }

    //回答机器人的问题
    private void huida(String daanStr) {
        haveWenti = false;
        mLog.e(" private void huida");
        //刷新答案
        int index = datas.size() - 1;
        ZhenxinhuaMsg bean = datas.get(index);
        bean.setDaan(daanStr);

//        datas.remove(index);
//        datas.add(index,bean);

        //移除原来的
        ZhenxinhuaMsgDao.update(context, bean);

//
//
//        //添加新的
//        ZhenxinhuaMsgDao.add(context, bean);

        //读取
        datas = ZhenxinhuaMsgDao.queryWithId(context, jid, cid);

        adapter.setData(datas);
        adapter.notifyDataSetChanged();
        if (datas != null) {
            listView.setSelection(datas.size());
            isShowTishi=true;
            setTishi();
        }
    }

    String wentiStr = "";
    String daanStr = "";

    boolean isResult = false;//是否是从选问题界面返回

    boolean haveWenti = false;//是否有机器人提了问题

    //向机器人提问
    private void send(String wentiStr, final String daanStr) {
        isWait=true;

        PreferencesUtils.putBoolean(context,jid+"isJinzhiWen",true);




        //1.合成一个ZhenxinhuaMsg
        ZhenxinhuaMsg msg = new ZhenxinhuaMsg();

        msg.setWenti(wentiStr);
        msg.setDaan(daanStr);
        msg.setType(ZhenxinhuaMsg.SEND);
        msg.setJid(jid);
        msg.setCid(cid);
        msg.setJicon(jicon);

        mLog.e("合成的真心话消息：" + new Gson().toJson(msg));

        //添加消息
        ZhenxinhuaMsgDao.add(context, msg);

        //2.合成一个ZhenxinhuaFriend
        ZhenxinhuaFriend friend = new ZhenxinhuaFriend();
        friend.setJid(jid);
        friend.setJicon(jicon);
        friend.setJname(jname);

        //添加好友
        zhenxinhuaFriendDao.add(context, friend);

        //真心话次数B自增一次
        int B = PreferencesUtils.getInt(context, jid + "ZhenCi", 0);
        B++;
        PreferencesUtils.putInt(context, jid + "ZhenCi", B);
        mLog.e(jid + "ZhenCi=自增后：" + B);

        //读取
        datas = ZhenxinhuaMsgDao.queryWithId(context, jid, cid);

        // 通过Handler启动等待线程
        mHandler.post(mRunnable);


        //5~9秒后，机器人自动回答
        int temp = 5 + new Random().nextInt(5);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // 将等待线程销毁掉
                mHandler.removeCallbacks(mRunnable);

                //刷新答案
                int index = datas.size() - 1;
                ZhenxinhuaMsg bean = datas.get(index);
                bean.setDaan(daanStr);

                datas.remove(index);
                datas.add(index, bean);

                adapter.setData(datas);
                adapter.notifyDataSetChanged();
                if (datas != null) {
                    listView.setSelection(datas.size());
                }
                // 播放音效
                soundPool.play(aid, 1, 1, 0, 0, 1);

                isResult = false;



                //5~10秒后开启自动回复机制，机器人问一个真心话
                int tmp = 5 + new Random().nextInt(6);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        receive();
                    }
                }, tmp * 1000);
            }

        }, temp * 1000);
    }

    /**
     * 弹出包月服务对话框
     */
    AlertDialog.Builder builder;
    AlertDialog alertDialog;

    private void tiaozhuanBaoyue() {

        mLog.e("弹出VIP服务对话框");
        View mView = LayoutInflater.from(context).inflate(R.layout.dialog_vipfuwu, null);
//        AbDialogUtil.showDialog(mView);

        builder = new AlertDialog.Builder(context, R.style.my_dialog);
//        builder.setView(mView);
        alertDialog = builder.create();

        alertDialog.setView(mView, 0, 0, 0, 0);
        alertDialog.setCancelable(false);
        alertDialog.show();

        TextView title = (TextView) mView.findViewById(R.id.title);
        TextView content = (TextView) mView.findViewById(R.id.content);
        TextView quxiao = (TextView) mView.findViewById(R.id.quxiao);
        TextView kaitong = (TextView) mView.findViewById(R.id.kaitong);

        title.setText("包月服务");
        content.setText("立即开通包月服务，和心爱的她畅聊吧");

        quxiao.setVisibility(View.GONE);
        kaitong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent it = new Intent().setClass(context, B15_faxinBaoyueActivity.class);
                startActivity(it);
                alertDialog.cancel();
            }
        });

    }

    /**
     * 接受机器人的真心话问题的方法
     * 1.从网络获取一个真心话问题
     * 2.封装成真心话消息
     * 3.保存到本地
     * 4.读取本地，并刷新视图
     */

    String wentiDefult = "点击回答问题……";

    private void receive() {


        haveWenti = true;
        mLog.e("进入接受机器人的真心话问题的方法");

        PreferencesUtils.putBoolean(context,jid+"isJinzhiWen",false);




        //1.从网络获取一个真心话问题
        BaseModel.setCallBackLister(new BaseModel.CallBackLister() {
            @Override
            public String onCallBack(String url, String data) {
                try{
                    List<ZHENXINHUA> list = new Gson().fromJson(data, new TypeToken<List<ZHENXINHUA>>() {
                    }.getType());
                    ZHENXINHUA zhenxinhua = list.get(0);
                    mLog.e("1.从网络获取一个真心话问题:" + new Gson().toJson(zhenxinhua));


                    ZhenxinhuaMsg msg = new ZhenxinhuaMsg();
                    msg.setJid(jid);
                    msg.setJicon(jicon);
                    msg.setCid(cid);
                    msg.setType(ZhenxinhuaMsg.RECEIVER);
                    msg.setWenti(zhenxinhua.getWenti());
                    msg.setDaan(wentiDefult);
                    mLog.e("2.封装成真心话消息:" + new Gson().toJson(msg));

                    ZhenxinhuaMsgDao.add(context, msg);

                    datas = ZhenxinhuaMsgDao.queryWithId(context, jid, cid);
                    adapter.setData(datas);
                    adapter.notifyDataSetChanged();
                    if (datas != null) {
                        listView.setSelection(datas.size());
                    }
                    // 播放音效
                    soundPool.play(aid, 1, 1, 0, 0, 1);

                    isWait=false;
                }catch (Exception e){
                    mLog.e("receive:异常"+e.getMessage());
                }

//                //弹出消息提醒(判断当前)
//                BmobNotifyManager bmobNotifyManager = BmobNotifyManager.getInstance(context);
//                Intent it = new Intent(context, B23_zhenxinhuaActivity.class);
//                it.putExtra("jid", jid);
//                it.putExtra("jicon", jicon);
//                bmobNotifyManager.showNotifyWithExtras(false, true, R.drawable.mylogo, "您有新的消息", jname, zhenxinhua.getWenti(), it);


                return url;
            }
        });
        RequestParams params = new RequestParams();
        params.addBodyParameter("id", jid);
        params.addBodyParameter("cid", cid);
        BaseModel.post(MyAPI.getzhenxinhua, params);


    }


    private Runnable mRunnable = new Runnable() {
        public void run() {
            // 更新界面
            mHandler.obtainMessage().sendToTarget();
            // 每1秒执行一次
            mHandler.postDelayed(mRunnable, 1000);
        }

    };

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            // 此处可以更新UI界面
            refreshDaan();
        }

    };

    int index = 0;

    private void refreshDaan() {
        String qianzui = "等待对方回答";
        String[] houzui = {".", "..", "...", "....", ".....", "......"};
        index++;
        int temp = index % 6;
        String text = qianzui + houzui[temp];
        //刷新等待
        int index = datas.size() - 1;
        ZhenxinhuaMsg bean = datas.get(index);
        bean.setDaan(text);

        datas.remove(index);
        datas.add(index, bean);

        adapter.setData(datas);
        adapter.notifyDataSetChanged();
        if (datas != null) {
            listView.setSelection(datas.size());
        }


//
//
//        daanTv.setText(text);

    }

    //提醒音效
    private SoundPool soundPool;
    int aid;

    //准备音效资源
    private void initSoudPool() {
        /***
         *  开始音效（SoudPool实现）
         */
        // 创建SoudPool的对象（最大音乐数目，音乐的类型，音乐的品质）
        soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
//        // 加载音乐
        aid = soundPool.load(context, R.raw.notify02, 1);
    }


}
